package com.digitalchina.dcn.dscc.portal.protocol;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Administrator on 2016/8/23 0023.
 */
public class PortalAttributeFacotry {

    private static final Logger logger = LoggerFactory.getLogger(PortalAttributeFacotry.class);

    /**
     * 创建用户名属性
     * @param username
     * @return
     */
    public static PortalAttribute createUsernameAttribute(String username) {
        return  createAttribute(PortalAttribute.Type.Username, username);
    }

    /**
     * 创建密码属性
     * @param password
     * @return
     */
    public static PortalAttribute createPasswordAttribute(String password) {
        return  createAttribute(PortalAttribute.Type.Password, password);
    }

    /**
     * 创建challenge属性
     * @param challenge
     * @return
     */
    public static PortalAttribute createChallengeAttribute(byte[] challenge) {
        return  new PortalAttribute(PortalAttribute.Type.Challenge, challenge);
    }

    /**
     * 生成ChapPassword属性
     * @param chapPassword
     * @return
     */
    public static PortalAttribute createChapPasswordAttribute(byte[] chapPassword) {
        return  new PortalAttribute(PortalAttribute.Type.ChapPassword, chapPassword);
    }

    private static PortalAttribute createAttribute(PortalAttribute.Type type, String value) {
        if (isValid(value)) {
            return new PortalAttribute(type, value);
        } else {
            return null;
        }
    }

    /**
     * 判断属性值是否有效。
     * 长度不能大于253，不能为空
     * @param attributeValue
     * @return
     */
    private static boolean isValid(String attributeValue) {
        if (StringUtils.isEmpty(attributeValue)) {
            logger.warn("attribute can't be null!");
            return false;
        } else if (attributeValue.length() > 253) {
            // attribute value的长度不能大于 253
            logger.warn("attribute-value's length can't bigger than 253 !");
            return false;
        }

        return true;
    }
}
